<template>
  <div>
    <el-dialog
      :title="this.$t('common.Add')"
      :visible.sync="Visible"
      width="1500px"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <div style="display:flex;">
        <div style="margin-right:10px;width:380px" class="dialogBox">
          <div style="flex-direction: column;" class="dialogBoxItem">
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.Title_poster')}}:
              </div>
              <div class="contant">
                <UploadImg
                  ref="logo"
                  @FileList="setFileList"
                ></UploadImg>
              </div>
            </div>
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.News_category')}}:
              </div>
              <div class="contant">
                <el-select
                  ref="category"
                  filterable
                  @blur="handleBlur('category', $event)"
                  @change="handleChang('category')"
                  v-model="data.category"
                  :placeholder="$t('common.select_plactholder')"
                >
                  <el-option
                    v-for="item in options_category"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.News_position')}}:
              </div>
              <div class="contant">
                <Multiselect
                  :select_labels="['name','sort']"
                  ref="position_id"
                  :modalName="'position_id'"
                  :select_model="data.position_id"
                  :select_options="options_position"
                  @selectBlur="selectBlur('position_id')"
                  @selectChang="MultiselectChange"
                >
                </Multiselect>
              </div>
            </div>
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.title')}}:
              </div>
              <div class="contant">
                <el-input
                  ref="title"
                  @blur="handleBlur('title',$event)"
                  @focus="handleFocus($event)"
                  :placeholder="$t('common.input_plactholder')"
                  v-model="data.title"
                ></el-input>
              </div>
            </div>
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.key_word')}}:
              </div>
              <div class="contant">
                <el-input
                  ref="tips"
                  @blur="handleBlur('tips',$event)"
                  @focus="handleFocus($event)"
                  :placeholder="$t('common.input_plactholder')"
                  v-model="data.tips"
                ></el-input>
              </div>
            </div>
            <div class="dialogBoxItemRow">
              <div class="title">
                <div class="RequiredRowTip">*</div>
                {{$t('newsManagementLang.release_time')}}:
              </div>
              <div class="contant">
                <el-date-picker
                  ref="publish_time"
                  @blur="Blur('publish_time')"
                  @focus="Focus('publish_time')"
                  v-model="data.publish_time"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm"
                  type="datetime"
                  :placeholder="$t('common.select_plactholder')"
                >
                </el-date-picker>
              </div>
            </div>
          </div>
        </div>
        <div style="width:calc(100% - 380px)" class="dialogBox">
          <div class="dialogBoxItem">
             <el-select
              style="display:none;"
              ref="videoSelect"
              @change="videoChange"
              filterable
              v-model="videoSrc"
              :placeholder="$t('common.select_plactholder')"
            >
              <el-option
                v-for="item in options_video"
                :key="item.id"
                :label="item.name"
                :value="item.video"
              >
              </el-option>
            </el-select>
            <div style="border: 1px solid rgb(204, 204, 204);width: 100%;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 525px;"
                  v-model="data.content"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
              />
          </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="preview" size="small"
          >{{$t('common.preview')}}</el-button
        >
        <el-button type="primary" @click="confirm" size="small"
          >{{$t('common.confirm')}}</el-button
        >
        <el-button @click="cancel" size="small">{{$t('common.cancel')}}</el-button>
      </span>
      
    </el-dialog>
    <Preview ref="preview"></Preview>
  </div>
</template>

<script>
import{updateImg} from "@/utils/HttpRequest"
import ElementUI from 'element-ui';
import {Editor, Toolbar } from '@wangeditor/editor-for-vue'
import UploadImg from "../../components/common/upload_Img";
import { DomEditor } from '@wangeditor/editor'
import Preview from "./newsManagement_right_add_preview.vue";
export default {
  components: { Editor, Toolbar, UploadImg,Preview},
  props: {
    // 接收绑定参数
    
  },
  data() {
    return {
      Visible: false,
      data: {
        logo:"",
        category:"",
        position_id:"",
        title:"",
        tips:"",
        content: '',
        publish_time:"",
      },
      videoSrc:'',//视频源
      options_video:[],
      lang_id:'',
      options_category:[],
      options_position:[],
      editor: null,
      toolbarConfig: {
        toolbarKeys : [
          "headerSelect",
          // "blockquote",
          "|",
          "bold",
          "underline",
          "italic",
          {
            iconSvg: '<svg t="1725619618336" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4310" width="128" height="128"><path d="M220.992 592a80 80 0 1 1 0-160 80 80 0 0 1 0 160zM512 592a80 80 0 1 1 0-160 80 80 0 0 1 0 160z m291.008 0a80 80 0 1 1 0-160 80 80 0 0 1 0 160z" fill="#2c2c2c" fill-opacity=".85" p-id="4311"></path></svg>', 
            key: 'group-more-style', 
            title: '更多', 
            menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle']
          },
          "color",
          "bgColor",
          "|",
          "fontSize",
          "fontFamily",
          "lineHeight",
          "|",
          {
            iconSvg: '<svg t="1725619469971" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3166" width="128" height="128"><path d="M187.392 70.656q28.672 0 48.64 19.456t19.968 48.128l0 52.224q0 28.672-19.968 48.64t-48.64 19.968l-54.272 0q-27.648 0-47.616-19.968t-19.968-48.64l0-52.224q0-28.672 19.968-48.128t47.616-19.456l54.272 0zM889.856 70.656q27.648 0 47.616 19.456t19.968 48.128l0 52.224q0 28.672-19.968 48.64t-47.616 19.968l-437.248 0q-28.672 0-48.64-19.968t-19.968-48.64l0-52.224q0-28.672 19.968-48.128t48.64-19.456l437.248 0zM187.392 389.12q28.672 0 48.64 19.968t19.968 48.64l0 52.224q0 27.648-19.968 47.616t-48.64 19.968l-54.272 0q-27.648 0-47.616-19.968t-19.968-47.616l0-52.224q0-28.672 19.968-48.64t47.616-19.968l54.272 0zM889.856 389.12q27.648 0 47.616 19.968t19.968 48.64l0 52.224q0 27.648-19.968 47.616t-47.616 19.968l-437.248 0q-28.672 0-48.64-19.968t-19.968-47.616l0-52.224q0-28.672 19.968-48.64t48.64-19.968l437.248 0zM187.392 708.608q28.672 0 48.64 19.968t19.968 47.616l0 52.224q0 28.672-19.968 48.64t-48.64 19.968l-54.272 0q-27.648 0-47.616-19.968t-19.968-48.64l0-52.224q0-27.648 19.968-47.616t47.616-19.968l54.272 0zM889.856 708.608q27.648 0 47.616 19.968t19.968 47.616l0 52.224q0 28.672-19.968 48.64t-47.616 19.968l-437.248 0q-28.672 0-48.64-19.968t-19.968-48.64l0-52.224q0-27.648 19.968-47.616t48.64-19.968l437.248 0z" p-id="3167"></path></svg>',
            key: "group-list",
            menuKeys: ['bulletedList', 'numberedList'],
            title: "列表"
          },
          // "bulletedList",
          // "numberedList",
          {
            iconSvg: '<svg viewBox=\"0 0 1024 1024\"><path d=\"M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z\"></path></svg>',
            key: "group-justify",
            menuKeys: ['justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify'],
            title: "对齐"
          },
          {
            iconSvg: "<svg viewBox=\"0 0 1024 1024\"><path d=\"M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z\"></path></svg>",
            key: "group-indent",
            menuKeys: ['indent', 'delIndent'],
            title: "缩进"
          },
          "uploadImage",
          "insertVideo",
          "|",
          "undo",
          "redo",
          "|",
          "fullScreen"
        ],
      },
      editorConfig: { 
        placeholder: this.$t('common.input_plactholder'),
        MENU_CONF : {
          // 其他配置...
          // 小于该值就插入 base64 格式（而不上传），默认为 0
          uploadImage:{
            // 自定义上传
            async customUpload(file, insertFn,aaa) {
              //最大上传nM图片
              let maxNum=3
              if(file.size>maxNum*1024*1024){
                let lang=JSON.parse(window.localStorage.getItem('language')).lang
                if(lang=='zh'){
                  ElementUI.Message.warning('最大上传'+maxNum+'M的图片！');
                }else if(lang=='en'){
                  ElementUI.Message.warning('Upload a maximum of '+maxNum+'M images!');
                }else if(lang=='ru'){
                  ElementUI.Message.warning('Максимальное количество фотографий '+maxNum+'M!');
                }else
                return
              }else{
                // JS 语法
                // file 即选中的文件
                let params = new FormData();
                params.append("wangeditor-uploaded-image", file);
                updateImg("uploadNewsImg",params).then((res) => {
                  // 自己实现上传，并得到图片 url alt href
                  // 最后插入图片
                  let randomNum=Math.random()*(100000-0)+0
                  insertFn(process.env.VUE_APP_BASE_URL+res.data.url,randomNum)
                });
              }
              
            }
          },
          insertVideo:{
            onInsertedVideo(videoNode) {
              if (videoNode == null) return
              videoNode.poster=videoNode.src+'?x-oss-process=video/snapshot,t_0,f_jpg'
              let str=JSON.parse(JSON.stringify(videoNode.src))+'#t=0.001'
              videoNode.src=str
            },
          },
        }  
      },
      mode: 'default', // or 'simple'   
      confirmTrue:true,//确定按钮保护
    };
  },
  created() {
   
  },
  mounted() {},
  watch: {},
  methods: {
    init(data) {
      this.lang_id=data
      this.getOptions()
      this.Visible = true;
      this.data.publish_time=this.setDay()
      this.data.content=''
    },
    //格式化当前时间
    setDay(time) {
      var date = new Date();
        if(!!time){
          date= new Date(time);
        }
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        let hh = date.getHours();
        let mf =
          date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        let ss =
          date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        let day =
          year +
          seperator1 +
          month +
          seperator1 +
          strDate +
          " " +
          hh +
          ":" +
          mf
        return day
    },
    setFileList(val){
      this.data.logo=val.raw
      if(!!this.data.logo){
        this.$refs.logo.$el.getElementsByClassName('el-upload')[0].style.border='1px solid #E0E3E9'
      }
    },
    //获取下拉单数据
    getOptions(){
      this.$get("getVideoList",{limit:-1}).then((res) => {
        this.options_video = res.data;
      });
      this.$get("langNews",{lang_id:this.lang_id}).then((res) => {
        this.options_category = res.data;
        if(this.options_category.length>0){
          this.data.category = this.options_category[0].id;
        }
      });
      this.$get("getNewPositionList",{lang_id:this.lang_id,limit:-1}).then((res) => {
        this.options_position = res.data;
      });
    },
    onCreated(editor) {
        this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        this.$nextTick(()=>{
          const toolbar = DomEditor.getToolbar(this.editor)
          const curToolbarConfig = toolbar.getConfig()
          editor.on('modalOrPanelShow', modalOrPanel => {
            if (modalOrPanel.type !== 'modal') return
            const { $elem } = modalOrPanel // modal element
            let babel_doms=$elem[0].getElementsByClassName('babel-container')
            // let select_dom=this.$refs.videoSelect.$el
            if(babel_doms[0].getElementsByTagName('input')[0].placeholder!=="视频文件 url 或第三方 <iframe>") return
            // babel_doms[0].getElementsByTagName('input')[0].style.display='none'
            // select_dom.style.display='block'
            // select_dom.getElementsByClassName('el-input__suffix-inner')[0].style.margin='6px 0'
                
            // babel_doms[0].appendChild(select_dom)
            babel_doms[1].style.display='none'   
          })
          editor.on('modalOrPanelHide', () => {
            this.videoSrc=''
          })
        })
    },
    preview(){
      let obj=JSON.parse(JSON.stringify(this.data))
      obj.content=this.setVideoSize()
      this.$refs.preview.init(obj)
    },
    // 提交
    confirm() {
      //是否有空值必选项标识
      let type = true;
      //输入框判断是否有值
      if(!this.data.logo){
        this.$refs.logo.$el.getElementsByClassName('el-upload')[0].style.border='1px solid red'
        type=false
      }
      if (!this.data.category&&this.data.category!==0) {
        this.$refs.category.$el.childNodes[1].childNodes[1].style.border =
          "1px solid red";
        type = false;
      }
      if (!this.data.position_id&&this.data.position_id!==0) {
        this.$refs.position_id.$el.childNodes[0].childNodes[1].childNodes[1].style.border ="1px solid red";
        type = false;
      }
      if(!this.data.title){
        this.$refs.title.$el.childNodes[1].style.border='1px solid red'
        type=false
      }
      if(!this.data.tips){
        this.$refs.tips.$el.childNodes[1].style.border='1px solid red'
        type=false
      }
      if(!this.data.publish_time){
        this.$refs.publish_time.$el.childNodes[1].style.border='1px solid red'
        type=false
      }
      if(!this.data.content){
        this.$refs.address_value.$el.childNodes[1].style.border='1px solid red'
        type=false
      }
      if (type && this.confirmTrue) {
        this.confirmTrue=false
        window.setTimeout(()=>{
          this.confirmTrue=true
        },1000);
        let params = new FormData();
        params.append("lang_id", this.lang_id);
        params.append("logo", this.data.logo);
        params.append("category", this.data.category);
        params.append("position_id", this.data.position_id);
        params.append("title", this.data.title);
        params.append("tips", this.data.tips);
        params.append("publish_time", new Date(this.data.publish_time).getTime()/1000);
        params.append("content", this.setVideoSize());
        this.$postForm("addNews", params).then((res) => {
          this.confirmTrue = true;
          if(res.success){
            this.$message.success(res.msg);
            this.$emit("success");
            this.cancel()
          }
        });
      }
    },
    setVideoSize(){
      let str=JSON.parse(JSON.stringify(this.data.content))
      const regex = new RegExp(`<video[^>]*>(.*?)<\/video>`, 'gi');
      let arr=str.match(regex)
      if(!!arr&&arr.length>0){
        arr.forEach(item=>{
          let newStr=item.replace('width="auto" height="auto"','width="100%" height="100%"')
          str=str.replace(item,newStr)
        })
      }
      return str
    },
    videoChange(){
      this.$refs.videoSelect.$el.previousElementSibling.value=this.videoSrc
    },
    //取消
    cancel() {
      this.data = {
        logo:"",
        category:"",
        position_id:"",
        title:"",
        tips:"",
        content:"",
        publish_time:"",
      };
      this.Visible = false;
      this.$refs.logo.handleRemove()
      let dom = document.getElementsByClassName("el-input__inner");
      for (let i = 0; i < dom.length; i++) {
         dom[i].style.border = "1px solid #E0E3E9";
      }
    },
    //输入框、下拉框失去焦点边框变色
    handleBlur(name, event) {
      if (!this.data[name]&&this.data[name]!==0) {
          event.target.style.border = "1px solid red";
        }
    },
    //输入框、下拉框获取焦点边框变色
    handleFocus(event) {
      event.target.style.border = "1px solid #E0E3E9";
    },
    handleChang(data) {
      if (this.data[data].length===0) {
          this.$refs[data].$el.childNodes[1].childNodes[1].style.border = "1px solid red";
        }else{
          this.$refs[data].$el.childNodes[1].childNodes[1].style.border ="1px solid #E0E3E9 ";
        }
    },
    // 判断了时间组件内容是否有东西
    Focus(name) {
      let dom = this.$refs[name].$el.childNodes[1]
      dom.style.border = "1px solid #E0E3E9";
      
    },
    Blur(name) {
      let dom = this.$refs[name].$el.childNodes[1]
      if (!this.data[name]) {
        dom.style.border = "1px solid red";
      }
    },
    //自定义多选下拉框
    selectBlur(name){
      if (this.data[name] === ""||!this.data[name]&&this.data[name]!==0) {
        this.$refs[name].$el.childNodes[0].childNodes[1].childNodes[1].style.border ="1px solid red";
      }
    },
    MultiselectChange(obj){
      this.data[obj.name]=obj.value
      if (this.data[obj.name].length===0) {
        this.$refs[obj.name].$el.childNodes[0].childNodes[1].childNodes[1].style.border = "1px solid red";
      }else{
        this.$refs[obj.name].$el.childNodes[0].childNodes[1].childNodes[1].style.border ="1px solid #E0E3E9 ";
      }
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped lang="less" >
  .dialogBox .dialogBoxItem {
    gap:20px;
    .dialogBoxItemRow{
      width: 100%;
    }
  }
  /deep/ .el-upload {
    .avatar-uploader-icon{
      width: 150px;
      height: 150px;
      line-height: 150px;
    }
    img{
      width: 150px;
      height: 150px;
    }
  } 
  /deep/ video{
    max-width: 98%;
  }
  // /deep/.w-e-text-container p{
  //   margin: 0;
  // }
</style>